#include "talkwindow.h"
#include "../QClient/QClientInterface.h"
#include <time.h>
#include <string>
#include <iostream>
#include <QFileDialog>
#include <QMessageBox>
using namespace std;

TalkWindow::TalkWindow(User& counterpart, QWidget* parent): QWidget(parent), ui(new Ui::TalkWindow)
{
    this->counterpart = counterpart;
    this->counterpart_gender = counterpart.gender;
    this->counterpart_ip = QString::fromStdString(counterpart.ip);
    this->counterpart_name = QString::fromStdString(counterpart.name);
    ui->setupUi(this);
    ui->historyEdit->setReadOnly(true);
    ui->nameLabel->setText(counterpart_name);
    ui->ipAddrLabel->setText(counterpart_ip);
    this->setWindowIcon(QIcon("./ico/logo16.png"));
    this->setWindowTitle(counterpart_name);
    if(counterpart_gender == male)
        ui->headLabel->setPixmap(QPixmap("./ico/male48.png"));
    else
        ui->headLabel->setPixmap(QPixmap("./ico/female48.png"));

    sc_send = new QShortcut(this);
    sc_send->setKey(QKeySequence(Qt::CTRL+Qt::Key_Return));
    connect(sc_send, SIGNAL(activated()), this, SLOT(showMyMsg()));
    connect(ui->sendMsgButton,SIGNAL(clicked()),this,SLOT(showMyMsg()));
    connect(ui->sendFileButton,SIGNAL(clicked()),this,SLOT(send_file()));

}

TalkWindow::~TalkWindow()
{
    delete ui;
}

void TalkWindow::showMyMsg()
{
    QString q_str = getCurrTime();
    q_str.append(QString("I say:\n"));
    QString msg = ui->msgEdit->toPlainText();
    q_str.append(msg);
    q_str.append(QString("\n"));
    ui->historyEdit->append(q_str);
    string str = msg.toStdString();
    sendMessage(str,counterpart);
}

void TalkWindow::showCounterpartMsg(QString& msg)
{
    QString q_str = getCurrTime();
    QString tmp = counterpart_name;
    tmp.append(QString(" says:\n"));
    q_str.append(tmp);
    q_str.append(msg);
    q_str.append(QString("\n"));
    ui->historyEdit->append(q_str);
}

QString TalkWindow::getCurrTime()
{
    char* time_c;
    string time_s;
    struct tm *curr_time;
    time_t t;
    t = time(NULL);
    curr_time = localtime(&t);
    time_c = asctime(curr_time);
    time_s = time_c;
    QString time_qs = QString::fromStdString(time_s);
    return time_qs;
}

void TalkWindow::closeEvent(QCloseEvent *event)
{
    string ip = counterpart_ip.toStdString();
    win_status_map[ip] = false;
    event->accept();
}

void TalkWindow::send_file()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Select File"), "", tr("All Files (*)"));
    string str = fileName.toStdString();
    // TODO : call to save file
    sendFile(str,counterpart);
}


